import React from 'react';
import style from './style';
import { Link, Button } from '../../ui-components';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as okrAction from '../../actions/okr.action';
import { updateGuide } from '../../actions/app.action';
import PeriodsSelect from './PeriodsSelect';
import util from '../../util';
import ReactCSSTransitionGroup from 'react/lib/ReactCSSTransitionGroup';

const btnMap = {
  1: [
    '当前周期尚未创建目标',
    '尚未创建公司目标',
    '您尚未设置团队',
  ],
  2: [
    '当前周期尚未创建目标',
    '所在团队尚未创建目标',
    '您尚未设置团队',
  ],
  3: [
    '当前周期尚未创建目标 ',
    '您尚未创建目标 ',
    '您尚未设置团队',
  ],
  4: [
    '当前周期尚未创建目标 ',
    '所在项目组尚未创建目标 ',
    '您尚未设置团队',
  ],
  5: [
    '当前周期没有我负责的目标 ',
    '您尚未创建目标 ',
    '您尚未设置团队',
  ],
}

@connect(({ okr, app }) => ({ okr, app }), dispatch => ({actions: bindActionCreators({...okrAction, updateGuide}, dispatch)}))
class ObjectBox extends React.Component {
  constructor(props) {
    super(props);
    this.displayName = 'ObjectBox';
    this.state = {
      periods: [],
      selectItem: {},
      okrs: '',
      parms: {},
    }
  }
  componentDidMount() {
    const {
      type = 1,
      ownerId,
    } = this.props;
    this.props.actions.fetchPeriodNew({type, ownerId}, (data) => {
      const selectItem = data.objectivePeriods.find((v) => v.default);
      this.setState({
        periods: data.objectivePeriods,
        selectItem: selectItem || {},
        okrs: selectItem ? '' : [],
      });
    });
  }
  componentWillUpdate(nextProps, nextState) {
    if(this.state.selectItem.objectivePeriodId !== nextState.selectItem.objectivePeriodId) {
      const flag = nextState.selectItem.objectivePeriodId;
      const {
        parms = {}
      } = nextProps;
      this.props.actions.fetchObjectiveNew(nextState.selectItem.objectivePeriodId, (data) => {
        if(flag === this.state.selectItem.objectivePeriodId)
          this.setState({
            okrs: data,
          });
      },{
        orderBy: 2,
        ...parms,
        ...this.state.parms,
      });
    } 
  }
  onChange = (v) => {
    this.setState({
      selectItem: v,
    });
  }
  getVoid = (i) => {
    const {
      type,
      parms = {},
    } = this.props;
    const msg = btnMap[parms.aboutMe ? 5 : type][i];
    return (
      <div className={style['void-area']} style={{
        backgroundImage: `url(/${util.getImagePath()}/default/void-${type === 4 ? '2-2' : type}${type===2?parms.aboutMe?'-1':'-2':''}.png)`
      }}>
        <div>{msg}</div>
        {i === 2 ? null :
          <div><Button onClick={()=>{this.toOkr(true)}} label={'前往创建'} className={style['btn']} /></div>
        }
      </div>
    )
  }
  toOkr = (flag, objectiveId) => {
    const {
      selectItem,
    } = this.state;
    const {
      app,
      type = 1,
    } = this.props;
    let parms = {
      type,
    };
    console.log(this.props);
    if(flag !== true)
      parms = {
        type,
        ...this.props.parms,
      }

    if (type == 1) {
      const { teamVO } = app.org;
      parms = {
        ...parms,
        teamId: (teamVO || {}).teamId
      };
    }
    else if (type == 2) {
      parms = {
        ...parms,
        // teamId: (app.profile.teamVO || {}).teamId
        teamId: this.props.ownerId
      }
    }
    else if (type ==3) {
      parms = {
        ...parms,
        userId: app.profile.userId,
        teamId: (app.profile.teamVO || {}).teamId
      };
    }
    else if (type == 4){
      parms = {
        ...parms,
        teamId: (app.profile.teamVO || {}).teamId,
        projectTeamId: this.props.ownerId
      };
    }

    if (objectiveId) { 
      window.open(`#/okr/objectives/${objectiveId}?${util.body(parms)}`);
      return;
    } 
    if(!selectItem.objectivePeriodId)
      window.open(`/#/okr?${util.body(parms)}`);
    else
      window.open(`/#/okr/${selectItem.objectivePeriodId}/objectives?${util.body(parms)}`);
  }
  render() {
    const {
      style: styles,
      title,
      isTop,
      app,
      canDrag,
      dragItem,
      topStyle
    } = this.props;
    const {
      periods,
      selectItem,
      okrs,
    } = this.state;

    return (
      <div className={style['object-box']} style={styles}>
        <div style={topStyle?topStyle:null} className={`${style['object-title']} ${canDrag ? style["object-drag-title"] : ""}`}>
          {canDrag ? dragItem : null}
          {title}
          {periods.length&&!isTop ? <PeriodsSelect list={periods} value={selectItem} onChange={this.onChange}/> : null}
        </div>
        <ReactCSSTransitionGroup 
          transitionName={{
            enter: style['opacity-enter'],
            enterActive: style['opacity-enter-active'],
            leave: style['opacity-leave'],
            leaveActive: style['opacity-leave-active'],
          }} 
          component={'div'} 
          transitionEnterTimeout={300} 
          transitionLeaveTimeout={300}
          className={style['opacity']}
        >
          { 
            typeof okrs === 'string' ? null : 
            isTop ? this.getVoid(2): 
            !periods.length ? this.getVoid(1) :
            !okrs.objectiveVOList.length ?
            this.getVoid(0):
            React.Children.map(this.props.children, (child, i)=> {
              return React.cloneElement(child, {
                app: app,
                okrs: okrs,
                toOkr: this.toOkr, 
                key: i,
                root: this.props.root
              });
            }, this)
          }
        </ReactCSSTransitionGroup>
        {
          periods.length && typeof okrs !== 'string' && okrs.objectiveVOList.length ? 
           <Link
              label={'查看全部'}
              onClick={() => {
                if (this.props.isTeam) {
                  this.props.actions.updateGuide(2);
                }
                this.toOkr();
              }}
              style={{
                position: 'absolute',
                bottom: '10px',
                right: '24px',
                color: '#7692b3'
              }}
            />
            : null
        }
      </div>
    );
  }
}

export default ObjectBox;
